package com.cheng.io.output;

import java.io.*;
import java.util.Date;

/**
 * 包装流和节点流可以随意组合
 */
public class ByteArrayOutputStreamTest02 {
    public static void main(String[] args) {
        try (
                // 节点流
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                // 包装流 对象输出流包装字节数组输出流
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        ) {
            // 向内存中的字节数组中写数据
            objectOutputStream.writeInt(100);
            objectOutputStream.writeObject(new Date());
            objectOutputStream.writeUTF("hello world");

            // 包装流需要手动刷新
            objectOutputStream.flush();

            // 获取内存中的字节数组
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            // for (byte b : byteArray) {
            //     System.out.println(b);
            // }
            
            // 使用字节数组输入流读取内存中字节数组中的数据
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            System.out.println("objectInputStream.readInt() = " + objectInputStream.readInt());
            System.out.println("objectInputStream.readObject() = " + objectInputStream.readObject());
            System.out.println("objectInputStream.readUTF() = " + objectInputStream.readUTF());

            // 关闭对象字节输入流
            // ....
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
